/**
 * Create by LDY 2020/4/13.<br>
 */
const canvasBg = "boardLevel_0", canvasSelf = "boardLevel_1", canvasRec = "boardLevel_2", canvasAll = "boardLevel_3";
const canvasHeigth = [1080, 900, 720, 540, 360];
const canvasWith = {1080: 1920, 900: 1600, 720: 1280, 540: 950, 360: 640};

const canvasWithArray = [1920, 1600, 1280, 950, 640];
const canvasWithDic = {1920: 1080, 1600: 900, 1280: 720, 950: 540, 640: 360};

const canvasFlag169 = 16 / 9;

const colorPen = {1: "#000000", 2: "#f44336", 3: "#4caf50", 4: "#2196f3", 5: "#ffc107", 6: "#9c27b0", 7: "#f5f5f5"}
const whiteBoardId = "whiteboard";
var initPoint = {x: 0, y: 0};
let leftDivWidth = 0; //左侧操作栏显示时的宽度,画笔在计算时需要考虑这个参数
/**
 * 一个坐标点()
 * 使用的是clientX, clientY 因为有其他布局遮挡，offsetX offsetY不能操作该区域
 *
 * @interface Point
 */
var Point = (function () {
    function Point(x, y) {
        if (x === void 0) {
            x = 0;
        }
        if (y === void 0) {
            y = 0;
        }
        this.x = x - leftDivWidth - initPoint.x;
        this.y = y - initPoint.y;

    }

    return Point;
})();
var PenDict = (function () {
    function PenDict(lineWith) {
        self.path = new Path2D();
        self.point = [];
        self.lineWith = lineWith
    }

    return PenDict;
})();


function newImage(imageData, cb) {
    var img = new Image();
    img.setAttribute('crossOrigin', 'anonymous');
    img.src = imageData;
    img.onload = function () {
        cb && cb(img);
    }
}

function penColorPenSplit(tempColorPen) {
    let length = tempColorPen.length;
    if (length == 7) {
        return tempColorPen;
    }
    if (length > 7) {
        return "#" + tempColorPen.substring(3);
    }
    return tempColorPen
}

/**
 * 画板
 * @param width
 * @param height
 */
function drawBoard(box, uuid) {
    var self = this;
    self.getViewportImgCmdId = 0;
    self.opType = 0;//0 表示白板 1 表示批注
    self.canvas_bg = null;//背景图
    self.canvas_send = null;//发送层
    self.uuid = uuid; // uuid
    if (box) {
      const doc = box.ownerDocument
      const curWindow = doc.defaultView || doc.parentWindow // 获取当前白板元素所在窗口
      self.max_canvas = curWindow.document.createElement("canvas"); // 大图
      self.max_canvas.width = 1920;
      self.max_canvas.height = 1080;
      self.max_canvas_context = self.max_canvas.getContext("2d")
      self.curWindow = curWindow

      self.canvas_all = curWindow.document.createElement("canvas");
      self.canvas_all.width = 1920;
      self.canvas_all.height = 1080;
      self.canvas_all_contxt = self.canvas_all.getContext("2d")
      self.boxDiv = box; // 白板元素
      self.Tdocument = curWindow.document;
    } else {
      self.boxDiv = null
      self.Tdocument = null
    }
    
    self.width = 100;
    self.height = 100;
    self.draw = null;
    self.drawType = 0;//0 表示 开启这 1 表示批注者
    self.timeout = 0;
    self.onBoardMouseDown = null;
    self.divClassName = "zj-whiteboard";
    self.bgImage = null; //底图背景image
    self.initPoint = {x: 0, y: 0};
    self.updateBoradTool = null;
    self.divWhiteBoard = null;
    self.screenshare = 0
    /**
     * 清空自己的Paths
     */
    drawBoard.prototype.clearSelfPaths = function (cb) {
        var self = this;
        if (!self.draw) {
            console.log("[clearSelfPaths]::draw is not exist");
            return;
        }
        let allPaths = [...self.draw.paths];
        self.draw.paths = allPaths.filter((value) => {
          return value['sender'] !== self.uuid
        })
        const delPaths = allPaths.filter((value) => {
          return value['sender'] == self.uuid
        })
        const delPathIds = delPaths.map(value => {
          return value.remoteCmid
        })
        self.draw.onMouseMoveSend(delPathIds, 1);
        cb && cb();
    }

    /**
     * 清空别人的Paths
     */
    drawBoard.prototype.clearOtherPaths = function (cb) {
      var self = this;
      if (!self.draw) {
        console.log("[clearOtherPaths]::draw is not exist");
        return;
      }
      let allPaths = [...self.draw.paths]; 
      self.draw.paths = allPaths.filter((value) => {
        return value['sender'] == self.uuid
      })
      const delPaths = allPaths.filter((value) => {
        return value['sender'] !== self.uuid
      })
      const delPathIds = delPaths.map(value => {
        return value.remoteCmid
      })
      self.draw.onMouseMoveSend(delPathIds, 1);
      cb && cb();
    }
    /**
     * 清空所有的Paths
     */
    drawBoard.prototype.clearAllPaths = function (cb) {
      var self = this;
      if (!self.draw) {
        console.log("[clearAllPaths]::draw is not exist");
        return;
      }
      let delPaths = [...self.draw.paths]; 
      self.draw.paths = []
      const delPathIds = delPaths.map(value => {
        return value.remoteCmid
      })
      self.draw.onMouseMoveSend && self.draw.onMouseMoveSend([], 2);
      cb && cb();
    }
    /**
     * 调整批注的div宽度高低
     * @param width
     * @param height
     * @param cb
     */
    drawBoard.prototype.canvasBoxDivInit = function (width, height, cb) {
        var self = this;
        if (self.boxDiv) {
            var boxWidth = width ? width : self.boxDiv.clientWidth;
            var boxHeight = height ? height : self.boxDiv.clientHeight;
            var xOffiex = 0;
            var yOffiey = 0;
            var flagb = boxWidth / boxHeight;
            if (flagb >= canvasFlag169) {
                //大于16：9 以高为算法
                boxWidth = boxHeight * canvasFlag169;
                xOffiex = Math.abs(self.boxDiv.clientWidth - boxWidth) / 2;
            }
            if (flagb < canvasFlag169) {
                boxHeight = boxWidth / canvasFlag169;
                yOffiey = Math.abs(self.boxDiv.clientHeight - boxHeight) / 2;
            }
            self.divWhiteBoard.style.width = boxWidth + "px";
            self.divWhiteBoard.style.height = boxHeight + "px";
            self.divWhiteBoard.style.marginLeft = xOffiex + "px";
            self.divWhiteBoard.style.marginTop = yOffiey + "px";
            initPoint.x = xOffiex + self.boxDiv.getBoundingClientRect().left;
            initPoint.y = yOffiey + self.boxDiv.getBoundingClientRect().top;
            self.initPoint = initPoint
        }
        cb && cb(boxWidth, boxHeight);
    }
    drawBoard.prototype.updateInitPoint = function () {
        if (self.boxDiv) {
            var boxWidth = self.boxDiv.clientWidth;
            var boxHeight = self.boxDiv.clientHeight;
            var canvasWidth = self.canvas_bg.width;
            var canvasHeight = self.canvas_bg.height;
            if (boxWidth > canvasWidth) {
                self.boxDiv.style.marginLeft = Math.abs(boxWidth - canvasWidth) / 2 + "px";
                initPoint.x = Math.abs(boxWidth - canvasWidth) / 2 + self.boxDiv.getBoundingClientRect().left;
            }
            if (boxHeight > canvasHeight) {
                self.boxDiv.style.marginTop = Math.abs(boxHeight - canvasHeight) / 2 + "px";
                initPoint.y = Math.abs(boxHeight - canvasHeight) / 2 + self.boxDiv.getBoundingClientRect().top;
            }
            self.initPoint = initPoint
        }

    }
    /**
     * 白板背景初始化
     */
    drawBoard.prototype.canvasbgInit = function (width, height, cb, screenshare) {
        var self = this;
        if (!self.canvas_bg) {
            var temp1 = self.createCanvasInit(null, width, height);
            if (!temp1) {
                cb && cb("canvas_bg fail.....");
            }
            self.canvas_bg = temp1[0];
            self.canvas_bg_context = temp1[1];
        }
        if (self.opType == 0) {
            //白板初始化
            self.canvas_bg_context.lineWidth = 1;//设置边框大写
            self.canvas_bg_context.fillStyle = !screenshare?"white":'rgba(0, 0, 0, 0)';//填充实体颜色
            self.canvas_bg_context.strokeRect(0, 0, width, height);//对边框的设置
            self.canvas_bg_context.fillRect(0, 0, width, height);//对内容的设置
            // 发送图片
            self.max_canvas_context.lineWidth = 1;//设置边框大写
            self.max_canvas_context.fillStyle = !screenshare?"white":'rgba(0, 0, 0, 0)';//填充实体颜色
            self.max_canvas_context.strokeRect(0, 0, self.max_canvas.width, self.max_canvas.height);//对边框的设置
            self.max_canvas_context.fillRect(0, 0, self.max_canvas.width, self.max_canvas.height);//对内容的设置
        } else if (self.opType == 1) {
            //批注初始化
            if (self.bgImage) {
                // self.canvas_bg_context.lineWidth = 1;//设置边框大写
                // self.canvas_bg_context.fillStyle = "#000";//填充实体颜色
                // self.canvas_bg_context.strokeRect(0, 0, width, height);//对边框的设置
                // self.canvas_bg_context.fillRect(0, 0, width, height);//对内容的设置
                self.getViewportImgCmdId++
                self.getViewportImg(self.getViewportImgCmdId, self.canvas_bg.width, self.canvas_bg.height, function (cmd_id, canvas) {
                  if (cmd_id < self.getViewportImgCmdId) {
                    console.log('SDK, canvasbgInit-- getViewportImg, return',cmd_id, self.getViewportImgCmdId)
                    return
                  }
                  let drawImage = self.bgImage
                  if (canvas) {
                    drawImage = canvas
                  }
                  let setArray = self.bgImageOffset(drawImage, self.canvas_bg.width, self.canvas_bg.height);
                  self.canvas_bg_context.drawImage(drawImage, setArray[0], setArray[1], setArray[2], setArray[3]);
                })
                // 发送图片
                // self.max_canvas_context.lineWidth = 1;//设置边框大写
                // self.max_canvas_context.fillStyle = "#000";//填充实体颜色
                // self.max_canvas_context.strokeRect(0, 0, width, height);//对边框的设置
                // self.max_canvas_context.fillRect(0, 0, width, height);//对内容的设置
                let setArray2 = self.bgImageOffset(self.bgImage, self.max_canvas.width, self.max_canvas.height);
                self.max_canvas_context.drawImage(self.bgImage, setArray2[0], setArray2[1], setArray2[2], setArray2[3]);

            }

        }
    }
    /**
     * 白板发送指令send 初始化
     */
    drawBoard.prototype.canvasSendInit = function (width, height, cb) {
        var self = this;
        if (!self.canvas_send) {
            var temp1 = self.createCanvasInit(null, width, height);
            if (!temp1) {
                cb && cb("canvas_send fail.....");
            }
            self.canvas_send = temp1[0];
            self.canvas_send_context = temp1[1];
        }
    }
    /**
     * 白板本端发送命令的初始化
     * @param width
     * @param height
     * @param cb
     */

    drawBoard.prototype.createWhiteBoardDiv = function () {
        var self = this;
        let zjbox = self.curWindow.document.querySelector(".zj-whiteboard")
        if(zjbox){
          self.divWhiteBoard = zjbox;
          return zjbox;
        }else{
          var obj = self.curWindow.document.createElement("div");
          obj.style.width = "100%";
          obj.style.height = "100%";
          obj.style.position = "relative";
          obj.setAttribute("class", self.divClassName + " cursor-pencil");
          self.divWhiteBoard = obj;
          return obj;
        }
    }
    /**
     * 开启白板初始化
     * @param obj
     * @param width
     * @param height
     * @param left
     * @param top
     * @constructor
     */
    drawBoard.prototype.createCanvasInit = function (obj, width, height, left, top) {
        var self = this;
        if (!obj) {
            // return;
            obj = self.curWindow.document.createElement("canvas");
            obj.style.position = "absolute";
            obj.style.left = "0";
            obj.style.pointerEvents = "none";
            // if (self.boxDiv) {
            //     var boxWidth = self.boxDiv.clientWidth;
            //     var boxHeight = self.boxDiv.clientHeight;
            //     if (boxWidth > width) {
            //         obj.style.marginLeft = Math.abs(boxWidth - width) / 2 + "px";
            //     }
            //     if (boxHeight > height) {
            //         obj.style.marginTop = Math.abs(boxHeight - height) / 2 + "px";
            //     }
            // }
        }
        obj.width = width;
        obj.height = height;

        var context = obj.getContext("2d");
        return [obj, context];
    }
    drawBoard.prototype.updateDrawPaths = function (opid, cmid) {
        var self = this;
        if (self.draw && self.draw.paths) {
          self.draw.paths.forEach(value => {
            if (value.opId == opid) {
              value.remoteCmid = cmid;
            }
          })
        }
    }
    /**
     * 获取图片
     * @param width
     * @param height
     * @param cb
     */
    drawBoard.prototype.getToImage = function () {
        var self = this;
        let canvasall = self.curWindow.document.createElement("canvas");
        var [width, height] = [self.max_canvas.width, self.max_canvas.height]
        canvasall.width = width;
        canvasall.height = height;
        let canvasAllContxt = canvasall.getContext("2d");
        canvasAllContxt.drawImage(self.max_canvas, 0, 0, width, height);

        canvasAllContxt.drawImage(self.canvas_send, 0, 0, width, height);
        return canvasall.toDataURL("image/png", 1);
    }
    /**
     * 开启白板 发起白板
     * @param width
     * @param height
     * @param cb
     */
    drawBoard.prototype.open = function (cb) {
        var self = this;
        if (!self.boxDiv) {
            console.debug("[whiteBoard]::boxDiv is null..");
            return;
        }
        var width = self.boxDiv.clientWidth;
        var height = self.boxDiv.clientHeight;

        var divElement = self.createWhiteBoardDiv();
        //修改zijingDiv
        self.canvasBoxDivInit(width, height, function (boxWidth, boxHeight) {
            self.canvasbgInit(boxWidth, boxHeight);
            self.canvasSendInit(boxWidth, boxHeight);
        });
        //背景图片
        divElement.appendChild(self.canvas_bg);
        divElement.appendChild(self.canvas_send);
        // 将3层canvas追加到白板div中
        self.boxDiv.appendChild(divElement);

        // self.canvas_bg_context.lineWidth = 1;//设置边框大写
        // self.canvas_bg_context.fillStyle = "white";//填充实体颜色
        // self.canvas_bg_context.strokeRect(0, 0, width, height);//对边框的设置
        // self.canvas_bg_context.fillRect(0, 0, width, height);//对内容的设置
        self.draw = new DrawPen(self.canvas_send);
        self.draw.parent = self;
        self.draw.DrawPenInit();

        //组合绘画
        function coverDrawImage(obj) {
            if (!obj || !obj.canvas_all_contxt || !obj.max_canvas) {
                clearInterval(self.timeout);
                self.timeout = 0;
                return;
            }
            obj.canvas_all_contxt.drawImage(obj.max_canvas, 0, 0, self.canvas_all.width, self.canvas_all.height);
            obj.canvas_all_contxt.drawImage(obj.canvas_send, 0, 0, self.canvas_all.width, self.canvas_all.height);
            // console.log("[drawBoard]::timeout::" + obj.timeout);
        }

        function initCanvers(obj) {
            self.timeout = setInterval(function () {
                coverDrawImage(obj);
            }, 500);
            return self.timeout;
        }

        initCanvers(self);
        self.draw.onMouseDown = function () {
            var self = this;
            if (self.parent.onBoardMouseDown) {
                self.parent.onBoardMouseDown();
            }
        }
        self.draw.onDrawLine = function (startPoint, endPoint) {
            clearInterval(self.timeout);
            self.timeout = 0;
            coverDrawImage(self);

        };
        self.draw.onMouseMove = function (event) {
            var self = this.parent;
            if (self.drawType == 0 && (!self.timeout || self.timeout == 0)) {
                self.timeout = initCanvers();
            }

        }
        /**
         * 发送指令
         */
        self.draw.onMouseMoveSend = function (data, flag) {
            var self = this.parent;
            if (self.setWhiteBoarding) {
              if (flag == 1 || flag == 2) {
                self.setWhiteBoarding(null, flag, null, data);
              } else {
                if (data && data.points.length > 1) {
                  self.setWhiteBoarding({
                      "penWidth": self.draw.penWidth,
                      "penColor": self.draw.penColor,
                      "width": self.canvas_send.width,
                      "height": self.canvas_send.height,
                      "array": data.points
                  }, flag, data.opId, data.remoteCmid);
                }
              }
            }
        }
        if (self.updateBoradTool) {
            self.updateBoradTool(1);
        }
        cb && cb();
    }
    // 组合画画
    drawBoard.prototype.coverDrawImage = function() {
      var self = this;
      // self.canvas_all_contxt = self.canvas_all.getContext("2d");
      self.canvas_all_contxt.drawImage(self.max_canvas, 0, 0, self.canvas_all.width, self.canvas_all.height);
      self.canvas_all_contxt.drawImage(self.canvas_send, 0, 0, self.canvas_all.width, self.canvas_all.height);
    }

    /**
     * 开启白板 pizhu
     * @param width
     * @param height
     * @param cb
     */
    drawBoard.prototype.openPizhu = function (cb, op, noPen, screenshare) {
        console.log('SDK-drawboard, openPizhu')
        var self = this;
        if (!self.boxDiv) {
            console.debug("[whiteBoard]::boxDiv is null..");
            return;
        }
          
        var width = self.boxDiv.clientWidth;
        var height = self.boxDiv.clientHeight;

        var divElement = self.createWhiteBoardDiv();
       
        //背景图片
        self.canvasBoxDivInit(width, height, function (nWidth, nHeight) {
            self.canvasbgInit(nWidth, nHeight, null, screenshare);
            self.canvasSendInit(nWidth, nHeight);
        });
        divElement.appendChild(self.canvas_bg);
        divElement.appendChild(self.canvas_send);
        // divElement.appendChild(zDiv);
        this.boxDiv.appendChild(divElement);
        self.draw = new DrawPen(self.canvas_send, "#000000");
        self.draw.parent = self;
        self.draw.initPoint = self.initPoint;
        if(!noPen){
          self.curWindow.document.getElementsByClassName("zj-whiteboard")[0].className = self.divClassName + " cursor-pencil";
          if (op == 1) {
              self.draw.DrawPenInit(1);
          } else {
              self.draw.DrawPenInit();
          }
          self.draw.onMouseDown = function () {
              var self = this;
              if (self.parent.onBoardMouseDown) {
                  self.parent.onBoardMouseDown();
              }
          }
          /**
           * 发送指令
           */
          self.draw.onMouseMoveSend = function (data, flag) {
              var self = this.parent;
              if (self.setWhiteBoarding) {
                if (flag == 1 || flag == 2) {
                  self.setWhiteBoarding(null, flag, null, data);
                } else if (data && data.points.length > 0) {
                  self.setWhiteBoarding({
                      "penWidth": self.draw.penWidth,
                      "penColor": self.draw.penColor,
                      "width": self.canvas_send.width,
                      "height": self.canvas_send.height,
                      "array": data.points
                  }, flag, data.opId, data.remoteCmid);
                }
              }
          }
        }else{
          //鼠标重置
          self.curWindow.document.getElementsByClassName("zj-whiteboard")[0].className = self.divClassName + " cursor";
        }
        if (self.updateBoradTool) {
            self.updateBoradTool(1);
        }
        cb && cb();
    }
    drawBoard.prototype.stopDrawBoard = function () {
        var self = this;
        clearInterval(self.timeout);
        if (self.canvas_bg) {
            self.canvas_bg.remove()
            self.canvas_bg = null;
            self.canvas_bg_context = null;
        }
        if (self.canvas_send) {
            self.canvas_send.remove()
            self.canvas_send = null;
            self.canvas_send_context = null;
        }
        if (self.max_canvas) {
            self.max_canvas.remove()
            self.max_canvas = null
            self.max_canvas_context = null
        }
        if (self.canvas_all) {
            self.canvas_all.remove()
            self.canvas_all = null
            self.canvas_all_contxt = null
        }
        if (self.draw) {
            self.draw.restoreEvent(false)
            self.draw.drawStop()
            if (self.draw.canvas) {
              self.draw.canvas.remove()
              self.draw.canvas = null
              self.draw.context = null
            }
        }
        self.draw = null;
        self.timeout = 0;
        self.bgImage = null;
        self.opType = 0;
        if (self.divWhiteBoard) {
            self.divWhiteBoard.remove();
            self.divWhiteBoard = null
        }
        if (self.updateBoradTool) {
            self.updateBoradTool(0);
        }
    }
    //停止画笔
    drawBoard.prototype.togglePen=function(type){
      var self = this;
      if(type==1){ //打开画笔
          self.curWindow.document.getElementsByClassName("zj-whiteboard")[0].className = self.divClassName + " cursor-pencil";
          self.draw.DrawPenInit();
          self.draw.onMouseDown = function () {
              var self = this;
              if (self.parent.onBoardMouseDown) {
                  self.parent.onBoardMouseDown();
              }
          }
          /**
           * 发送指令
           */
          self.draw.onMouseMoveSend = function (data, flag) {
              var self = this.parent;
              if (self.setWhiteBoarding) {
                if (flag == 1 || flag == 2) {
                  self.setWhiteBoarding(null, flag, null, data);
                } else if (data && data.points.length > 0) {
                  self.setWhiteBoarding({
                    "penWidth": self.draw.penWidth,
                    "penColor": self.draw.penColor,
                    "width": self.canvas_send.width,
                    "height": self.canvas_send.height,
                    "array": data.points
                  }, flag, data.opId, data.remoteCmid);
                }
              }
          }
      }else{ // 关闭画笔
        if (self.draw) {
          self.draw.drawStop();
          self.curWindow.document.getElementsByClassName("zj-whiteboard")[0].className = self.divClassName +" cursor";
        }
      }

    }
    /**
     * 还原canvans笔画
     * @param owidth
     * @param oheight
     * @param nwidth
     * @param nheight
     * @param type
     * @param cb
     */
    drawBoard.prototype.restoreCanvasSend = function (cava, contxt, owidth, oheight, nwidth, nheight, cb) {
        var self = this;
        let opaths = self.draw.paths;
        cava.width = nwidth;
        cava.height = nheight;
        let flagx = cava.width / owidth;
        let flagy = cava.height / oheight;
        if (nwidth == 0 || nheight == 0) {
          return
        }
        
        for (let i = 0; i < opaths.length; i++) {
            contxt.beginPath();
            contxt.lineCap = "round";
            //接受远端颜色
            let penColor = penColorPenSplit(opaths[i].penColor);
            contxt.strokeStyle = penColor;
            contxt.lineWidth = opaths[i].penWidth;
            let points = opaths[i].points;
            let newPoints = [];
            let beginPoint = {};
            let newPath = new Path2D();
            for (let j = 0; j < points.length; j++) {
                points[j].x = points[j].x * flagx;
                points[j].y = points[j].y * flagy;
                newPoints.push(points[j]);
                if (newPoints.length >= 3) {
                    var lastTwoPoints = newPoints.slice(-2);
                    var controlPoint = lastTwoPoints[0];
                    var endPoint = {
                        x: (lastTwoPoints[0].x + lastTwoPoints[1].x) / 2,
                        y: (lastTwoPoints[0].y + lastTwoPoints[1].y) / 2,
                    }

                    contxt.globalCompositeOperation = "source-over";
                    let tempPath = new Path2D();
                    // self.context.moveTo(beginPoint.x, beginPoint.y);
                    tempPath.moveTo(beginPoint.x, beginPoint.y);
                    // self.context.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
                    tempPath.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
                    newPath.addPath(tempPath);
                    contxt.stroke(tempPath);
                    beginPoint = endPoint;
                }
            }
            opaths[i].path = newPath;
            opaths[i].points = newPoints;
        }
        if(self.draw){
            self.draw.updateDrawSendPaths(opaths);
        }
    }
    
    drawBoard.prototype.updateCanvasV2 = function (cb, isFullScreen) {
        if (!self.canvas_send) {
            return;
        }
        var width = self.boxDiv.clientWidth;
        var height = self.boxDiv.clientHeight;
        // if(isFullScreen){
        //   if(isFullScreen==1){
        //     if (self.canvas_send.width >= width && self.canvas_send.height >= height) {
        //       return;
        //     }
        //   }else{
        //     if (self.canvas_send.width <= width && self.canvas_send.height <= height) {
        //       return;
        //     }
        //   }
        // }else{
        //   if (self.canvas_send.width >= width && self.canvas_send.height >= height) {
        //     return;
        // }
        // }
        
       
        self.canvasBoxDivInit(width, height, function (newWidth, newHeight) {
            try {
              
              //背景层还原
              if (self.opType == 0) {
                  //白板还原
                  self.canvas_bg.width = newWidth;
                  self.canvas_bg.height = newHeight;
                  self.canvas_bg_context.lineWidth = 1;//设置边框大写
                  if (self.screenshare) {
                    self.canvas_bg_context.fillStyle = 'rgba(0, 0, 0, 0)';//填充实体颜色
                    self.canvas_bg_context.strokeStyle = 'rgba(0, 0, 0, 0)';//填充边框颜色
                  } else {
                    self.canvas_bg_context.fillStyle = "white";//填充实体颜色
                    self.canvas_bg_context.strokeStyle = "red";//填充边框颜色
                  }
                  self.canvas_bg_context.strokeRect(0, 0, newWidth, newHeight);//对边框的设置
                  self.canvas_bg_context.fillRect(0, 0, newWidth, newHeight);//对内容的设置
              }
              if (self.bgImage) {
                  self.canvas_bg_context = self.canvas_bg.getContext("2d");
                  self.canvas_bg.width = newWidth;
                  self.canvas_bg.height = newHeight;
                  self.getViewportImgCmdId++
                  self.getViewportImg(self.getViewportImgCmdId, newWidth, newHeight, function (cmd_id, canvas) {
                    if (cmd_id < self.getViewportImgCmdId) {
                      console.log('SDK-updateCanvasV2 getViewportImg, return', cmd_id, self.getViewportImgCmdId)
                      return
                    }
                    let drawImage = self.bgImage
                    if (canvas) {
                      drawImage = canvas
                    }
                    let setArray = self.bgImageOffset(drawImage, self.canvas_bg.width, self.canvas_bg.height);
                    self.canvas_bg_context.drawImage(drawImage, setArray[0], setArray[1], setArray[2], setArray[3]);
                  })
              }
              // 笔画还原
              let owidth = self.canvas_send.width
              let oheight = self.canvas_send.height
              if (owidth == 0 || oheight == 0) {
                owidth = self.owidth
                oheight = self.oheight
              } else {
                self.owidth = owidth
                self.oheight = oheight
              }
              if (newWidth == 0 || newHeight == 0) {
                return
              }
              self.draw && self.restoreCanvasSend(self.canvas_send, self.canvas_send_context, owidth, oheight, newWidth, newHeight);

              cb && cb();
            } catch(e) {
              console.log('SDK- canvasBoxDivInit call back error')
              console.log(e)
            }
        });


    }
    /**
     * 补充画笔 更新白板
     *
     * @param data
     */
    drawBoard.prototype.rePenDrawLine = function (oData, cb, imageBase64) {
        var self = this;
        if(!self.canvas_bg){
          return;
        }
        if (oData.op == 'reload_background') {
          if(!self.canvas_bg_context){
            self.canvas_bg_context = self.canvas_bg.getContext("2d")
          }
          var bg = new Image();
        
          //图片资源加载时异步的。必须保证图片资源加载完成后才行
          bg.setAttribute('crossOrigin', 'anonymous');
          bg.src = imageBase64
          bg.onload = function() {
            self.bgImage = bg;
            self.canvas_bg_context.clearRect(0, 0, self.canvas_bg.width, self.canvas_bg.height);
            let setArray = self.bgImageOffset(bg, self.canvas_bg.width, self.canvas_bg.height);
            self.canvas_bg_context.drawImage(bg, setArray[0], setArray[1], setArray[2], setArray[3]);

            self.max_canvas_context.clearRect(0, 0, self.max_canvas.width, self.max_canvas.height);
            let setArray2 = self.bgImageOffset(bg, self.max_canvas.width, self.max_canvas.height);
            self.max_canvas_context.drawImage(bg, setArray2[0], setArray2[1], setArray2[2], setArray2[3]);
          }
          
        } else if(oData.op == 'clear'){ //清除所有
          self.draw.context.clearRect(0, 0, self.draw.canvas.width,  self.draw.canvas.height);
          self.draw.paths = [];
          // 绘制当前未完成的笔画
          self.drawlocalPoints()
        }else {
            self.remoteDrawPen([oData], cb, null);
            cb && cb();
        }
    }
    /**
     * 调整背景位移量
     * @param oimage
     * @param cwidth
     * @param cheight
     */
    drawBoard.prototype.bgImageOffset = function (oimage, cwidth, cheight) {
        let setImageWidth = oimage.width;
        let setImageHeight = oimage.height;

        // let oImageFix = setImageWidth / setImageHeight; // 图片宽高比
        // let cImageFix = cwidth / cheight; // 画布宽高比
        // 计算缩放比例  
        const scaleRatio = Math.min(cwidth / setImageWidth, cheight / setImageHeight);
        // if (cwidth > setImageWidth && cheight > setImageHeight) {
        //     //宽和高都高于原图
        //     setImageWidth = cwidth;
        //     setImageHeight = cwidth / oImageFix;
        // }
        // if (cwidth > setImageWidth && cheight <= setImageHeight) {
        //     //宽高于原图
        //     setImageHeight = cheight;
        //     setImageWidth = setImageHeight * oImageFix;
        //     setImageOffcetX = (cwidth - setImageWidth) / 2;
        // }
        // if (cwidth <= setImageWidth && cheight <= setImageHeight) {
        //     //宽高都小于原图
        //     setImageHeight = cheight
        //     setImageWidth = setImageHeight * oImageFix;
        // }
        // if (cwidth <= setImageWidth && cheight > setImageHeight) {
        //     //高高于原图
        //     setImageHeight = cheight
        //     setImageWidth = setImageHeight * oImageFix;
        //     setImageOffcetY = (cheight - setImageHeight) / 2;
        // }
        setImageWidth *= scaleRatio
        setImageHeight *= scaleRatio
        let setImageOffcetX = (cwidth - setImageWidth)/2;
        let setImageOffcetY = (cheight - setImageHeight)/2;
        return [Math.floor(setImageOffcetX), Math.floor(setImageOffcetY), setImageWidth, setImageHeight];
    }
    /**
     * 初始化蒙板的大小调整
     * @param obj
     * @param width
     * @param height
     * @param left
     * @param top
     * @returns {*}
     * @constructor
     */
    drawBoard.prototype.createCanvasPostioin = function (obj, width, height, left, top) {
        var setheight = height, setWidth = width;
        if (!obj) {
            obj = self.curWindow.document.createElement("canvas");
        }
        var temp169 = (width / height);
        if (temp169 > canvasFlag169) {
            setheight = (height - 20);
            top = "10px";
            setWidth = Math.floor(setheight * (canvasFlag169 + 0.05));
            if (temp169 > 2) {
                setheight = Math.floor(setWidth / temp169);
                top = Math.floor((height - setheight) / 2);
            }
            left = (width - setWidth) / 2;
        } else {
            setWidth = width;
            for (let i = 0; i < canvasWithArray.length; i++) {
                if (setWidth > canvasWithArray[i]) {
                    setheight = canvasWithDic[canvasWithArray[i]] - 20;
                    break;
                }
            }
            // setheight = setWidth / (canvasFlag169 + 0.05);
            left = 0;
            top = 0;
            top = (height - setheight) / 2;
        }
        obj.height = setheight;
        obj.width = setWidth;

        $(obj).css("top", top);
        $(obj).css("left", left);

        return obj;


    }
    /*
     * 绘制当前未完成的画笔
    */
    drawBoard.prototype.drawlocalPoints = function () {
        var self = this;
        const arrays = self.draw.points
        if (arrays.length < 3) {
          return
        }
        let points = []
        let beginPoint = {}
        let context = self.canvas_send_context

        if (!context) {
            return;
        }
           
        context.beginPath();
        context.lineCap = self.draw.lineCap;
        context.strokeStyle = self.draw.penColor;
        context.lineWidth = self.draw.penWidth;
        for (let i = 0; i < arrays.length; i++) {
            points.push(arrays[i]);
            if (points.length >= 3) {
                var lastTwoPoints = points.slice(-2);
                var controlPoint = lastTwoPoints[0];
                var endPoint = {
                    x: (lastTwoPoints[0].x + lastTwoPoints[1].x) / 2,
                    y: (lastTwoPoints[0].y + lastTwoPoints[1].y) / 2,
                }
                // context.moveTo(beginPoint.x, beginPoint.y);
                // context.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);

                context.globalCompositeOperation = "source-over";
                context.beginPath();
                let tempPath = new Path2D();
                // self.context.moveTo(beginPoint.x, beginPoint.y);
                tempPath.moveTo(beginPoint.x, beginPoint.y);
                // self.context.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
                tempPath.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
                context.stroke(tempPath);
                beginPoint = endPoint;
            }
        }
    }
    /**
     * 接受远端画笔
     */
    drawBoard.prototype.remoteDrawPen = function (data, cb) {
        var self = this;

        function delRemoatePen(cmid) {
            // 先清除
            let selfPaths = [...self.draw.paths];
            if (Array.isArray(cmid)) {
              cmid.forEach(id => {
                selfPaths.forEach(function (value, i) {
                  if (value["remoteCmid"] == id && self.draw.paths.includes(value)) {
                    self.draw.paths.splice(self.draw.paths.indexOf(value), 1)
                  }
                });
              })
            } else {
              selfPaths.forEach(function (value, i) {
                  if (value["remoteCmid"] == cmid && self.draw.paths.includes(value)) {
                    self.draw.paths.splice(self.draw.paths.indexOf(value), 1)
                  }
              });
            }
            // 清空重新绘制
            self.draw.context.clearRect(0, 0, self.draw.canvas.width,  self.draw.canvas.height);
            self.draw.paths.forEach(function(item,index) {
              self.draw.context.lineWidth = item.penWidth;
              self.draw.context.strokeStyle = item.penColor;
              self.draw.context.stroke(item.path);
            })
            // 绘制当前未完成的笔画
            self.drawlocalPoints()
          }

        for (let j = 0; j < data.length; j++) {
            let tempData = data[j];
            let cmdid = tempData.cmdid;
            if (tempData.op == 'delete') {
              delRemoatePen(cmdid);
              return;
            }
            let tdataPayload = tempData.payload;
            let sender = tempData.sender;
            //远端的宽和高
            let rWidth = tdataPayload.width;
            let rHeight = tdataPayload.height;

            let arrays = tdataPayload.array;
            let points = [];
            let beginPoint = {};
            let context = self.canvas_send_context

            if (!context) {
                return;
            }
           
            context.beginPath();
            context.lineCap = "round";
            //接受远端颜色
            let penColor = penColorPenSplit(tdataPayload.penColor);
            context.strokeStyle = penColor;
            context.lineWidth = tdataPayload.penWidth;
            let path = new Path2D();
            for (let i = 0; i < arrays.length; i++) {
                let width = self.canvas_send.width ? self.canvas_send.width : self.owidth
                let height = self.canvas_send.height ? self.canvas_send.height : self.oheight
                arrays[i].x = arrays[i].x * (width / rWidth);
                arrays[i].y = arrays[i].y * (height / rHeight);

                points.push(arrays[i]);
                if (points.length >= 3) {
                    var lastTwoPoints = points.slice(-2);
                    var controlPoint = lastTwoPoints[0];
                    var endPoint = {
                        x: (lastTwoPoints[0].x + lastTwoPoints[1].x) / 2,
                        y: (lastTwoPoints[0].y + lastTwoPoints[1].y) / 2,
                    }
                    // context.moveTo(beginPoint.x, beginPoint.y);
                    // context.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);

                    context.globalCompositeOperation = "source-over";
                    context.beginPath();
                    let tempPath = new Path2D();
                    // self.context.moveTo(beginPoint.x, beginPoint.y);
                    tempPath.moveTo(beginPoint.x, beginPoint.y);
                    // self.context.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
                    tempPath.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
                    path.addPath(tempPath);
                    context.stroke(tempPath);
                    beginPoint = endPoint;
                }
            }
            if(tempData.op != 'delete'){
              let hascmdid=self.draw.paths.find(function (item) {
                return item.remoteCmid==cmdid
              })
              if(!hascmdid){
                self.draw.paths.push({
                  opId: Date.now(),
                  path: path,
                  penColor: penColor,
                  penWidth: tdataPayload.penWidth,
                  remoteCmid: cmdid,
                  sender: sender,
                  points: points
                });
              }    
            } 
        }
        cb && cb();
    }
    /**
     * 修改替换底图
     * @param width
     * @param height
     */
    drawBoard.prototype.updageBgCanvans = function (base64Data, cb) {
        console.log('SDK-drawboard updageBgCanvans')
        var self = this;
        if(self.canvas_bg_context){
            self.canvas_bg_context.clearRect(0, 0, self.canvas_bg.width, self.canvas_bg.height);
        }
        newImage(base64Data, function (tmpImg) {
            if (!self.canvas_bg) {
              console.log('SDK---updageBgCanvans, newImage no canvas_bg')
              return
            }
            self.bgImage = tmpImg;
            self.getViewportImgCmdId++
            self.getViewportImg(self.getViewportImgCmdId, self.canvas_bg.width, self.canvas_bg.height, function (cmd_id, canvas) {
              if (cmd_id < self.getViewportImgCmdId) {
                console.log('SDK---updageBgCanvans- getViewportImg,return',cmd_id, self.getViewportImgCmdId)
                return
              }
              let drawImage = self.bgImage
              if (canvas) {
                drawImage = canvas
              }
              let setArray = self.bgImageOffset(drawImage, self.canvas_bg.width, self.canvas_bg.height);
              self.canvas_bg_context.drawImage(drawImage, setArray[0], setArray[1], setArray[2], setArray[3]);
            })

            self.max_canvas_context.drawImage(self.bgImage, 0, 0, self.max_canvas.width, self.max_canvas.height);
            cb && cb();
        });
    }
    /**
     * 开启批注
     * @param width
     * @param height
     */
    drawBoard.prototype.openAnnotateCanvas = function (data, ismark, imageData, cb, noPen, screenshare) {
        console.log('SDK-drawboard, openAnnotateCanvas')
        var self = this;
        self.drawType = 1;
        self.screenshare = screenshare
        if (ismark) {
            self.opType = 1;
            // , data[0].payload.width
            // , data[0].payload.height
            newImage(imageData, function (tmp) {
                self.bgImage = tmp;
                self.openPizhu(function () {
                        self.remoteDrawPen(data, null);
                        cb && cb();
                    }, 1,noPen, screenshare);
            });
        } else {
            self.opType = 0;
            self.bgImage = null;
            self.openPizhu(function () {
                    self.remoteDrawPen(data, null);
                    cb && cb();
                },null, noPen, screenshare);
        }
    }
    /**
     * 修改画笔的初始值
     * @param penWidth
     * @param color
     * @param isXPC
     */
    drawBoard.prototype.updatePenInit = function (penWidth, color, isXPC) {

        var self = this;
        if (!self.draw) {
            return;
        }
        if (penWidth) {
            self.draw.penWidth = penWidth;
        }
        if (color) {
            self.draw.penColor = color;
        }
        self.draw.isXPC = isXPC ? true : false;
        if (self.draw.isXPC) {
            self.curWindow.document.getElementsByClassName("zj-whiteboard")[0].className = self.divClassName +" cursor-easer";
            self.draw.restoreEvent(false);
        } else {
            self.curWindow.document.getElementsByClassName("zj-whiteboard")[0].className = self.divClassName +" cursor-pencil";
            self.draw.restoreEvent(true);
        }
    }
    /**
     * canvans 全局参数
     * @param penWidth
     * @param color
     * @param isXPC
     * @param status //清空类型 1所有 2自己 3其他人
     */
    drawBoard.prototype.updatePenCanvans = function (operate,status) {

        var _this = this;
        if (!self.draw) {
            return;
        }
        switch (operate) {
            case 0:
                // 只清空自己的笔画数据
                _this.clearSelfPaths(function () {
                    // _this.draw.clearCanvas();
                    _this.draw.clearCanvas(2);
                });
                break;
            case 1:
                //  清空 
                _this.draw.clearCanvas(status);
                break;
            case 2:
                //保存本地
                _this.saveCanvasDown('jpeg');
                break;
        }
    }
    //图片下载操作,指定图片类型
    drawBoard.prototype.saveCanvasDown = function (type) {
        var _this = this;
        var imgdata = null;
        //设置保存图片的类型
        if (_this.opType == 1) {
            imgdata = _this.getToImage();
        } else {
            imgdata = _this.canvas_all.toDataURL(type, 1);
        }
        //将mime-type改为image/octet-stream,强制让浏览器下载
        var fixtype = function (type) {
            type = type.toLocaleLowerCase().replace(/jpg/i, 'jpeg');
            var r = type.match(/png|jpeg|bmp|gif/)[0];
            return 'image/' + r;
        }
        imgdata = imgdata.replace(fixtype(type), 'image/octet-stream')
        //将图片保存到本地
        var saveFile = function (data, filename) {
            var link = self.curWindow.document.createElement('a');
            link.href = data;
            link.download = filename;
            var event = self.curWindow.document.createEvent('MouseEvents');
            event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            link.dispatchEvent(event);
        }
        var filename = new Date().toLocaleDateString() + '.' + type;
        saveFile(imgdata, filename);
    }

    // 获取画笔信息
    drawBoard.prototype.getDrawPen = function () {
        return {
            penColor: self.draw.penColor || "#FF605C",
            penWidth: self.draw.penWidth || 5
        }
    }

    // 修改左侧边框的宽度
    drawBoard.prototype.changeLeftDivWidth = function (width) {
        leftDivWidth = width;
    }
}

/**
 * 画笔
 * @param canvasObj
 * @param penColor
 * @param penWidth
 * @param contextObj
 * @constructor
 */
function DrawPen(canvasObj, penColor, penWidth, contextObj) {
    var self = this;
    if(typeof penWidth !== "number") penWidth = 5;
    self.parent = null;
    /** 画笔颜色 */
    self.penColor = penColor ? penColor : "#FF605C";
    /** 画笔宽度直径 */
    self.penWidth = penWidth;
    /** 每次绘制长度阈值（值越小绘制频率越高，曲线越平滑） */
    self.drawDistance = self.penWidth / 2;
    /** 线帽类型 */
    self.lineCap = "round";
    /** 橡皮擦类型 */
    self.isXPC = false;
    self.canvas = canvasObj;
    self.canvas.perent = self;
    self.context = contextObj ? contextObj : self.canvas.getContext("2d");
    self.path = null;
    self.paths = [];
    /** 最后一次绘制的坐标点 */
    self.lastPoint = {x: 0, y: 0};
    /** 当前绘制的坐标点 */
    self.currPoint = {x: 0, y: 0};
    /** 是否鼠标按下 */
    self.isMouseDown = false;
    /** 画板初始化 */
    self.onMouseDown = null;
    self.onMouseMove = null;
    self.onMouseUp = null;
    self.onDrawCurveStart = null;
    self.onDrawCurveEnd = null;
    self.onDrawLine = null;
    self.drawLineArray = [];
    self.arcTimeout = 100;//橡皮擦延时器
    self.x1;
    self.y1;
    //塞尔关键点的算法
    self.points = [];//集合点
    self.begnPoint = null;

    self.changeDiv = {"isChangeMove": 0};
    self.initPoint = {x: 0, y: 0};

    DrawPen.prototype.updateDrawSendPaths = function (newPaths) {
        var self = this;
        self.paths = newPaths;
    }
    DrawPen.prototype.drawStop = function () {
        var _this = this;

        _this.parent.divWhiteBoard && _this.parent.divWhiteBoard.removeEventListener("mousedown", _this.mousedownQuadra, false);
        _this.parent.divWhiteBoard && _this.parent.divWhiteBoard.removeEventListener("mouseleave", _this.mouseleaveQuadra, false);
        _this.parent.divWhiteBoard && _this.parent.divWhiteBoard.removeEventListener("mouseover", _this.mouseoverQuadra, false);
        _this.parent.divWhiteBoard && _this.parent.divWhiteBoard.removeEventListener("mousemove", _this.mousemoveQuadra, false);
        _this.parent.divWhiteBoard && _this.parent.divWhiteBoard.removeEventListener("mouseup", _this.mouseupQuadra, true);
        _this.parent.Tdocument && _this.parent.Tdocument.removeEventListener("mousemove", _this.mousemoveQuadr, false);
        _this.parent.Tdocument && _this.parent.Tdocument.removeEventListener("mouseup", _this.mouseupQuadra, true);
    }
    DrawPen.prototype.DrawPenInit = function (op) {
        var _this = this;

        _this.parent.divWhiteBoard.perent = _this;
        _this.parent.Tdocument.perent = _this;
        _this.parent.divWhiteBoard.addEventListener("mousedown", _this.mousedownQuadra, false);
        _this.parent.divWhiteBoard.addEventListener("mouseleave", _this.mouseleaveQuadra, false);
        _this.parent.divWhiteBoard.addEventListener("mouseover", _this.mouseoverQuadra, false);
        if (op == 1) {
            _this.parent.divWhiteBoard.addEventListener("mousemove", _this.mousemoveQuadra, false);
            _this.parent.divWhiteBoard.addEventListener("mouseup", _this.mouseupQuadra, true);
        } else {
            _this.parent.Tdocument.addEventListener("mousemove", _this.mousemoveQuadra, false);
            _this.parent.Tdocument.addEventListener("mouseup", _this.mouseupQuadra, true);
        }

        // 监听浏览器窗口宽高变更
        // window.onresize = resetCanvasSize;
    }
    /**
     * 移除移动事件
     */
    DrawPen.prototype.restoreEvent = function (flag) {
        var _this = this;
        if (flag) {
            _this.parent.Tdocument && _this.parent.Tdocument.removeEventListener("mousemove", _this.mousemoveQuadra, false);
            _this.parent.Tdocument && _this.parent.Tdocument.removeEventListener("mouseup", _this.mouseupQuadra, true);
            _this.parent.Tdocument && _this.parent.Tdocument.addEventListener("mousemove", _this.mousemoveQuadra, false);
            _this.parent.Tdocument && _this.parent.Tdocument.addEventListener("mouseup", _this.mouseupQuadra);
        } else {
            _this.parent.Tdocument && _this.parent.Tdocument.removeEventListener("mousemove", _this.mousemoveQuadra, false);
            _this.parent.Tdocument && _this.parent.Tdocument.removeEventListener("mouseup", _this.mouseupQuadra);
        }

    }
    /**
     * 清除所有的笔画
     */
    DrawPen.prototype.clearCanvas = function (status) {
        var _this = this;  
        console.log(_this)  
        //清除所有画笔       
        if(status==1){ //所有       
          _this.parent.clearAllPaths()
        }else if(status==2){//自己
          _this.parent.clearSelfPaths();
        }else if(status==3){ //其他人
          _this.parent.clearOtherPaths();               
        }
        // 重新绘制
        _this.parent.draw.context.clearRect(0, 0, _this.parent.draw.canvas.width,  _this.parent.draw.canvas.height);
        _this.parent.draw.paths.map(function(item,index) {
          _this.parent.draw.context.lineWidth = item.penWidth;
          _this.parent.draw.context.strokeStyle = item.penColor;
          _this.parent.draw.context.stroke(item.path);
        })
        
    }
    /**
     * 清除一笔画path
     */
    DrawPen.prototype.clearCipLinePath = function (e) {
        var _this = this;
        let x = e.clientX - leftDivWidth  - initPoint.x, y = e.clientY - initPoint.y;
        let penWidth = _this.penWidth;
        let oldPenWidth = _this.penWidth;
        _this.context.lineCap = _this.lineCap;
        let dela = [];
        let exitArray = [];
        let oldPath = _this.paths;
        _this.paths.forEach(function (value, i) {
            if (_this.context.isPointInStroke(_this.paths[i].path, x, y) && value.sender == _this.parent.uuid) {
                dela.push(value);
            } else {
                exitArray.push(_this.paths[i]);
            }
        });
        if (dela.length > 0) {
            _this.context.strokeStyle = "#FFFFFF";

            _this.paths = exitArray;
            _this.context.clearRect(0, 0, _this.canvas.width, _this.canvas.height);
            _this.paths.forEach(function (value, i) {
                penWidth = _this.paths[i].penWidth;
                _this.context.lineWidth = penWidth;
                _this.context.strokeStyle = _this.paths[i].penColor;
                _this.context.stroke(_this.paths[i].path);
            });
            const delPathIds = dela.map(value => {
              return value.remoteCmid
            })
            // 发送删除信令
            if (_this.onMouseMoveSend) {
                _this.onMouseMoveSend(delPathIds, 1);
            }
        }
        _this.context.lineWidth = oldPenWidth;

    }
    /**
     * 塞尔关键点的算法
     * @param e
     */
    DrawPen.prototype.mousedownQuadra = function (e) {
        e.preventDefault();
        // is drawPen 对象
        var self = this.perent;
        if (self.isXPC) {
            self.clearCipLinePath(e);
            return;
        }
        self.path = new Path2D();
        if (self.onMouseDown) {
            self.onMouseDown(e);
        }
        self.isMouseDown = true;
        var point = new Point(e.clientX, e.clientY);
        self.points.push(point);
        self.beginPoint = point;
        self.lastPoint = point;
        self.currPoint = point;
        // self.drawLine(true);
    }

    /**
     *鼠标离开元素
     * @param e
     */
    DrawPen.prototype.mouseleaveQuadra = function (e) {
        var self = this.perent;
        if (e.currentTarget.className.indexOf("zj-whiteboard") > -1) {
            //是指的当前白板准备移动到另外的div
            // self.changeDiv.isChangeMove = 1;

        }
        if (e.toElement) {
            if (typeof e.toElement.className == 'string' && e.toElement.className.indexOf("zj-whiteboard") > -1) {
                self.changeDiv.isChangeMove = 0;
            } else {
                self.changeDiv.isChangeMove = 1;
                self.changeDiv["toWidth"] = e.toElement.offsetWidth;
                self.changeDiv["toHegith"] = e.toElement.offsetHeight;
                self.changeDiv["spoint"] = {x: e.clientX, y: e.clientY};
                console.log(e.toElement.offsetWidth + "---" + e.toElement.offsetHeight);
            }
        } else {
            self.changeDiv.isChangeMove = 0;
        }
    }
    DrawPen.prototype.mouseoverQuadra = function (e) {
        var self = this.perent;
        self.changeDiv.isChangeMove = 0;

    }
    /**
     * 鼠标移动
     * @param e
     */
    DrawPen.prototype.mousemoveQuadra = function (e) {
        var self = this.perent;
        if (!self.isMouseDown) {
            return;
        }
        if (self.onMouseMove) {
            self.onMouseMove(e);
        }
        if (self.isXPC) {
            self.tapmoveHandler(e);
        } else {
            var point = new Point(e.clientX, e.clientY);
            if (self.changeDiv.isChangeMove) {

            }
            self.points.push(point);
            if (self.points.length > 3) {
                var lastTwoPoints = self.points.slice(-2);
                var controlPoint = lastTwoPoints[0];
                var endPoint = {
                    x: (lastTwoPoints[0].x + lastTwoPoints[1].x) / 2,
                    y: (lastTwoPoints[0].y + lastTwoPoints[1].y) / 2,
                }
                self.drawLineQuadra(self.beginPoint, controlPoint, endPoint);
                self.beginPoint = endPoint;
            }

        }

    }
    /**
     * 鼠标抬起笔画
     * @param e
     */
    DrawPen.prototype.mouseupQuadra = function (e) {
        var self = this.perent;
        self.isMouseDown = false;
        if (self.isXPC) {
            self.cleraClipEnd();
            return;
        }
        if (self.points.length > 3) {
            var lastTwoPoints = self.points.slice(-2);
            var controlPoint = lastTwoPoints[0];
            var endPoint = lastTwoPoints[1];
            self.drawLine(self.beginPoint, controlPoint, endPoint);
        }
        self.beginPoint = null;
        // isDown = false;
        let parmPath;
        if (self.points.length > 0) {
            parmPath = {
                "path": self.path,
                "points": self.points,
                "penWidth": self.penWidth,
                "penColor": self.penColor,
                "remoteCmid": 0,
                "opId": Date.now(),
                'sender': self.parent.uuid,
            };
            self.paths.push(parmPath);
        }
        self.points = [];
        if (self.onMouseMoveSend) {
            // self.onMouseMove(parmPath);
            self.onMouseMoveSend(parmPath);
        }

    }
    DrawPen.prototype.cleraClipEnd = function () {
        var self = this;
        //检测擦除状态
        self.arcTimeout = setTimeout(function () {
            var imgData = self.context.getImageData(0, 0, self.canvas.width, self.canvas.height);
            var dd = 0;
            var distance = self.penWidth * 1.5;
            for (var x = 0; x < imgData.width; x += distance) {
                for (var y = 0; y < imgData.height; y += distance) {
                    var i = (y * imgData.width + x) * 4;
                    if (imgData.data[i + 3] > 0) {
                        dd++
                    }
                }
            }
            if (dd / (imgData.width * imgData.height / (distance * distance)) < 0.4) {
                self.canvas.className = "noOp";
            }
        }, 100);

    }
    /**
     * 创建一个Point点
     *
     * @returns {Point}
     */
    DrawPen.prototype.createPoint = function () {
        return {x: 0, y: 0};
    }
    DrawPen.prototype.drawCurveStart = function (e, startPoint) {
        var self = this;
        if (self.onDrawCurveStart) {
            self.onDrawCurveStart(startPoint);
        }
        if (self.isXPC) {
            self.cleraClipDown(e);
        } else {
            self.drawLine(true);
        }

    }

    DrawPen.prototype.tapmoveHandler = function (e) {
        var self = this;
        clearTimeout(self.arcTimeout);
        e.preventDefault();

        var area = self.getClipArea(e, false);

        var x2 = area.x;
        var y2 = area.y;

        self.clearClipArc(self.penWidth * 1.5, self.x1, self.y1, x2, y2);

        self.x1 = x2;
        self.y1 = y2;
    }
    /**
     * 橡皮擦 擦除
     * @param e
     */
    DrawPen.prototype.clearClipArc = function (raidus, x1, y1, x2, y2) {
        var self = this;

        self.context.save();
        self.context.beginPath();
        if (arguments.length == 3) {
            self.context.arc(x1, y1, raidus, 0, 2 * Math.PI);
            self.context.fill();
        } else {
            self.context.moveTo(x1, y1);
            self.context.lineTo(x2, y2);
            self.context.stroke();
        }
        self.context.restore();
        if (self.onDrawLine) {
            x2 = x2 ? x2 : x1;
            y2 = y2 ? y2 : y1;
            self.onDrawLine(new Point(x1, y1), new Point(x2, y2));
        }
    }
    /**
     * 橡皮擦点击事件
     * @param e
     */
    DrawPen.prototype.cleraClipDown = function (e) {
        var self = this;
        self.context.lineCap = "round";
        self.context.lineJoin = "round";
        self.context.lineWidth = self.penWidth * 2;
        self.context.globalCompositeOperation = "destination-out";
        clearTimeout(self.arcTimeout);
        e.preventDefault();
        var area = self.getClipArea(e, false);
        var x1 = area.x;
        var y1 = area.y;
        self.x1 = x1;
        self.y1 = y1;
        self.clearClipArc(self.penWidth * 1.5, x1, y1);
    }
    /**
     * 获取橡皮擦清除的缓存
     * @param e
     */
    DrawPen.prototype.getClipArea = function (e, hastouch) {
        var self = this;
        // var x = hastouch ? e.targetTouches[0].pageX : e.clientX;
        // var y = hastouch ? e.targetTouches[0].pageY : e.clientY;

        var x = hastouch ? e.targetTouches[0].pageX : e.clientX;
        var y = hastouch ? e.targetTouches[0].pageY : e.clientY;
        var ndom = self.canvas;

        // while (ndom.tagName !== "BODY") {
        //     x -= ndom.offsetLeft;
        //     y -= ndom.offsetTop;
        //     ndom = ndom.parentNode;
        // }
        return {
            x: x,
            y: y
        }

    }

    DrawPen.prototype.drawTextLine = function (point, text) {
        var self = this;
        self.context.font = "48px serif";
        self.context.strokeText(text, point.x, point.y);
    }
    /**
     * 笔画
     * @param beginPoint
     * @param controlPoint
     * @param endPoint
     */
    DrawPen.prototype.drawLineQuadra = function (beginPoint, controlPoint, endPoint) {
        
        var self = this;
        // withFlag = withFlag ? withFlag : 1;
        // heightFlag = heightFlag ? heightFlag : 1;
        self.context.globalCompositeOperation = "source-over";
        if (!self.isMouseDown) return;

        // self.context.save();
        self.context.beginPath();
        self.context.lineCap = self.lineCap;
        self.context.strokeStyle = self.penColor;
        self.context.lineWidth = self.penWidth;
        let path = new Path2D();
        // self.context.moveTo(beginPoint.x, beginPoint.y);
        path.moveTo(beginPoint.x, beginPoint.y);
        // self.context.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
        path.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
        self.path.addPath(path);
        self.context.stroke(path);
        // self.context.closePath();
        // self.context.restore();
        // console.log(`[drawBoard] zhu send ::--${JSON.stringify(beginPoint)}--${JSON.stringify(controlPoint)}--${JSON.stringify(endPoint)}`);
        // if (self.onDrawLine) {
        //     self.onDrawLine(self.lastPoint, self.currPoint);
        // }
    }
    DrawPen.prototype.drawLine = function (isForce, withFlag, heightFlag, isRemote) {
      // console.log('画画')
        var self = this;
        withFlag = withFlag ? withFlag : 1;
        heightFlag = heightFlag ? heightFlag : 1;
        self.context.globalCompositeOperation = "source-over";
        if (isForce === void 0) {
            isForce = false;
        }
        if (!self.isMouseDown) return;
        var d = self.distance(self.lastPoint, self.currPoint);
        // console.log(d);
        if (isForce || d >= self.drawDistance) {
            self.context.save();
            self.context.beginPath();
            self.context.lineCap = self.lineCap;
            self.context.strokeStyle = self.penColor;
            self.context.lineWidth = self.penWidth;
            self.context.moveTo(self.lastPoint.x * withFlag, self.lastPoint.y * heightFlag);
            self.context.lineTo(self.currPoint.x * withFlag, self.currPoint.y * heightFlag);
            self.context.stroke();
            self.context.closePath();
            self.context.restore();
            if (isRemote) {
                return;
            }
            if (self.onDrawLine) {
                self.onDrawLine(self.lastPoint, self.currPoint);
            }

            self.lastPoint.x = self.currPoint.x;
            self.lastPoint.y = self.currPoint.y;
        }
    }
    /**
     * 计算两点间距离
     *
     * @param {Point} pt
     * @param {Point} pt2
     * @returns
     */
    DrawPen.prototype.distance = function (pt, pt2) {
        return Math.sqrt(Math.pow(pt2.x - pt.x, 2) + Math.pow(pt2.y - pt.y, 2));
    }

}
